//
//  NetworkingHandler.m
//  UI29_Block
//
//  Created by dllo on 16/1/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetworkingHandler.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@implementation NetworkingHandler

//+ (void)networkingWithURL:(NSString *)string completeHandle:(void (^)(id))block {
//    
//    /** 字符串转码 */
//    NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    
//    NSURL *url = [NSURL URLWithString:codeString];
//    
//    NSURLSession *session = [NSURLSession sharedSession];
//    
//    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        
//        
//        /** 回到主线程(GCD) */
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            if (data) {
//                
//                /** 数据解析 */
//                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//                
//                /** 调用block */
//                block(result);
//            }
//            
//   
//        });
//  
//    }];
//    
//    
//    [dataTask resume];
//    
//    
//}

+ (void)networkingWithURL:(NSString *)string completeHandle:(void (^)(NSData *data, id))block {
    
#pragma mark - 判断网络状态
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"网络不给力");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    
    if (isExistenceNetwork) {
        
        /** 字符串转码 */
        NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:codeString]];
        
        /** 方法post */
   //     request.HTTPMethod = @"GET";
        /** body如果是get可为空 */
    //    request.HTTPBody = nil;
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        //
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data) {
                
                NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
               // NSString *cook = @"caches";
                NSString *behind = @".data";
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
              
                NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:codeString],behind]];
                
                [data writeToFile:path  atomically:YES];
                // NSLog(@"%@", path);
                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                // 调用 block
                // 回到主线程(GCD)
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    block(data, result);
                    
                });
                
            }
            
        }];
        
        [task resume];
 
    } else {
        
        NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

        NSLog(@"网络不给力");
        NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
      //  NSString *cook = @"caches";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:codeString],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        if (data == nil) {
            
            return;
            
        } else {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            block(data, result);
        }
        
        
    }
   
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}


@end
